package com.heima.user.filter;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppUserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@Slf4j
@WebFilter(value = "appTokenFilter", urlPatterns = "/*")
@Order(1)
public class AppTokenFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取请求头中的userId
        String userId = request.getHeader("userId");
        if(StringUtils.isNotBlank(userId)&&Integer.valueOf(userId)!=0){
            //将apUser封装到当前线程中
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            AppUserThreadLocalUtils.setUser(apUser);
        }
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
